<template>
  <div class="page-content padding">
    <div class="page-main">
      <a-form :form="form" labelAlign="left">
        <a-row>
          <a-col span="24">
            <a-form-item label="接口地址" :labelCol="labelCol"
                         :wrapperCol="wrapperCol">
              <a-input placeholder="请输入接口地址，API接口数据只支持HTTP和HTTPS进行调用"
                       v-decorator="['interfacePath',{ rules: [{ required: true, message: '接口地址不能为空' }]}]"/>
            </a-form-item>
          </a-col>
          <a-col span="24">
            <a-form-item :label="'请求方式'" :labelCol="labelCol"
                         :wrapperCol="wrapperCol">
              <a-select v-decorator="['requestMethod',{initialValue: '0', rules: [{ required: true, message: '分类不能为空' }]}]"
                        style="width: 100%" placeholder="请选择请求方式"
              >
                <a-select-option value="0">
                  POST
                </a-select-option>
                <a-select-option value="1">
                  GET
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div>
        <a-tabs @change="tabChange" :activeKey="tableActiveKey">
          <a-tab-pane key="0" tab="请求参数">
            <div class="margin-bottom-xs">
              <a-button type="primary" icon="plus" @click="handleAdd('requestParams')">新建参数</a-button>
              <a-button class="cu-btn-danger margin-left-xs" type="link" @click="handleDelAll('requestParams')">一键删除
              </a-button>
            </div>
            <a-form :form="rpTableForm">
              <a-table :customRow="rpCustomRow" bordered :data-source="requestParamsSource"
                       :columns="requestParamsColumns" size="small" rowKey="id" :pagination="false">
                <span slot="serial" slot-scope="text, record, index">
                  <a-icon type="drag"/>
                  {{ index + 1 }}
							  </span>
                <template v-for="col in [ 'paramsName','paramsValue','description']"
                          :slot="col"
                          slot-scope="text, record, index"
                >
                  <a-form-item>
                    <a-input v-decorator="[
                            col + record.id + 'requestParams',
                            { initialValue: text, rules: getOptionRules(col) },
                            ]"
                             allowClear
                             @change="e => handleChange(e.target.value, index, col,'requestParams')"/>
                  </a-form-item>
                </template>
                <template slot="action" slot-scope="text, record, index">
                  <a-popconfirm title="确定删除吗？" @confirm="() => handleDel(index,'requestParams')">
                    <a class="action-delete">删除</a>
                  </a-popconfirm>
                </template>
              </a-table>
            </a-form>
          </a-tab-pane>
          <a-tab-pane key="1" tab="请求头部" :forceRender="true">
            <div class="margin-bottom-xs">
              <a-button type="primary" icon="plus" @click="handleAdd('requestHeader')">新建参数</a-button>
              <a-button class="cu-btn-danger margin-left-xs" type="link" @click="handleDelAll('requestHeader')">一键删除
              </a-button>
            </div>
            <a-form :form="rhTableForm">
              <a-table :columns="requestHeaderColumns" :data-source="requestHeaderSource" :bordered="false" size="small"
                       rowKey="id"
                       :pagination="false" :customRow="rhCustomRow">
                <span slot="serial" slot-scope="text, record, index">
                  <a-icon type="drag"/>
                  {{ index + 1 }}
							  </span>
                <div class="margin-xs">
                  <a-button type="primary" icon="plus" @click="handleAdd('requestHeader')">新建字段</a-button>
                </div>
                <template v-for="col in ['paramsName','paramsValue','description']"
                          :slot="col"
                          slot-scope="text, record, index"
                >
                  <a-form-item>
                    <a-input v-decorator="[
                            col + record.id + 'requestHeader',
                            { initialValue: text, rules: getOptionRules(col) },
                            ]"
                             allowClear
                             @change="e => handleChange(e.target.value, index, col,'requestHeader')"
                             :key="col + record.id + 'requestHeader'"
                    />
                  </a-form-item>
                </template>
                <template slot="action" slot-scope="text, record, index">
                  <a-popconfirm title="确定删除吗？" @confirm="() => handleDel(index,'requestHeader')">
                    <a class="action-delete">删除</a>
                  </a-popconfirm>
                </template>
              </a-table>
            </a-form>
          </a-tab-pane>
        </a-tabs>
      </div>

    </div>
  </div>
</template>

<script>
  import pick from 'lodash.pick';

  const fields = ['interfacePath', 'requestMethod'];
  let columns = [
    {
      title: "序号",
      width: 50,
      fixed: 'left',
      align: "center",
      dataIndex: "serial",
      scopedSlots: {customRender: "serial"},
    },
    {
      title: '参数名',
      dataIndex: 'paramsName',
      scopedSlots: {customRender: 'paramsName'},
    }, {
      title: '参数值',
      dataIndex: 'paramsValue',
      scopedSlots: {customRender: 'paramsValue'},
    }, {
      title: '参数描述',
      dataIndex: 'description',
      scopedSlots: {customRender: 'description'},
    }, {
      title: '操作',
      dataIndex: 'action',
      scopedSlots: {customRender: 'action'},
    },
  ]
  export default {
    name: "apiSetting",
    components: {},
    data() {
      return {
        form: this.$form.createForm(this),
        rpTableForm: this.$form.createForm(this),
        rhTableForm: this.$form.createForm(this),
        model: {},
        labelCol: {
          xs: {
            span: 24,
          },
          sm: {
            span: 3,
          },
        },
        wrapperCol: {
          xs: {
            span: 24,
          },
          sm: {
            span: 21,
          },
        },
        requestParamsSource: [
          {id: 0}
        ],
        requestHeaderSource: [{id: 0}],
        requestParamsColumns: columns,
        requestHeaderColumns: columns,
        requestParamsCount: 1,
        requestHeaderCount: 1,
        sourceObj: {},
        targetObj: {},
        tableActiveKey: '0',
      }
    },
    mounted() {
      // 防止表单未注册
      fields.forEach((v) => this.form.getFieldDecorator(v));
      // 当 model 发生改变时，为表单设置值
      this.$watch("model", () => {
        this.model && this.form.setFieldsValue(pick(this.model, fields));
        if(this.model){
          console.log(this.model)
          let requestParameters = this.model?.requestParameters?JSON.parse(this.model.requestParameters):[{id: 0}]
          let requestHeadParameters = this.model?.requestHeadParameters?JSON.parse(this.model.requestHeadParameters):[{id: 0}]
          this.requestParamsSource = requestParameters ? requestParameters : [{id: 0}]
          this.requestHeaderSource = requestHeadParameters ? requestHeadParameters : [{id: 0}]
        }
        //  给请求参数和请求头部数据加上id
      });
    },
    methods: {
      //初始化页面
      innitData() {
        this.form.resetFields()
        this.rpTableForm.resetFields()
        this.rhTableForm.resetFields()
        this.tableActiveKey = '0'
        this.requestParamsSource = [
          {id: 0}
        ]
        this.requestHeaderSource = [{id: 0}]
        this.requestParamsCount = 1
        this.requestHeaderCount = 1
      },
      //一键清除
      handleDelAll(type) {
        let that = this
        that.$confirm({
          title: '提示',
          content: '确定删除该数据吗？删除之后不可恢复！',
          okText: '确定',
          cancelText: '取消',
          icon: () => that.$createElement('a-icon', {
            props: {
              key: 'warning',
              type: 'exclamation-circle',
              twoToneColor: '#faad14'
            }
          }),
          onOk() {
            if (type == 'requestParams') {
              that.requestParamsSource = [{id: 0}]
            } else {
              that.requestHeaderSource = [{id: 0}]
            }
          }
        })
      },
      // 拖拽
      rpCustomRow(record, index) {
        return {
          props: {
            draggable: 'true'
          },
          style: {
            cursor: 'grab'
          },
          on: {
            // 鼠标移入
            mouseenter: (event) => {
              // 兼容IE
              var ev = event || window.event
              ev.target.draggable = true
            },
            // 开始拖拽
            dragstart: (event) => {
              // 兼容IE
              var ev = event || window.event
              // 阻止冒泡
              ev.stopPropagation()
              // 得到源目标数据
              this.sourceObj = record
            },
            // 拖动元素经过的元素
            dragover: (event) => {
              // 兼容 IE
              var ev = event || window.event
              // 阻止默认行为
              ev.preventDefault()
            },
            // 鼠标松开
            drop: (event) => {
              // 兼容IE
              var ev = event || window.event
              // 阻止冒泡
              ev.stopPropagation()
              // 得到目标数据
              this.targetObj = record
              const tempData = this.requestParamsSource

              tempData[this.targetObj.weight] = this.sourceObj
              tempData[this.sourceObj.weight] = this.targetObj

              let weightList = []
              tempData.forEach((item, index) => {
                weightList.push({
                  id: item.id,
                  weight: index,
                  paramsName: item.paramsName,
                  paramsValue: item.paramsValue,
                  description: item.description,
                })
              })
              this.requestParamsSource = weightList
            }
          }
        }
      },
      rhCustomRow(record, index) {
        return {
          props: {
            draggable: 'true'
          },
          style: {
            cursor: 'grab'
          },
          on: {
            // 鼠标移入
            mouseenter: (event) => {
              // 兼容IE
              var ev = event || window.event
              ev.target.draggable = true
            },
            // 开始拖拽
            dragstart: (event) => {
              // 兼容IE
              var ev = event || window.event
              // 阻止冒泡
              ev.stopPropagation()
              // 得到源目标数据
              this.sourceObj = record
            },
            // 拖动元素经过的元素
            dragover: (event) => {
              // 兼容 IE
              var ev = event || window.event
              // 阻止默认行为
              ev.preventDefault()
            },
            // 鼠标松开
            drop: (event) => {
              // 兼容IE
              var ev = event || window.event
              // 阻止冒泡
              ev.stopPropagation()
              // 得到目标数据
              this.targetObj = record
              const tempData = this.requestHeaderSource
              tempData[this.targetObj.weight] = this.sourceObj
              tempData[this.sourceObj.weight] = this.targetObj
              let weightList = []
              tempData.forEach((item, index) => {
                weightList.push({
                  id: item.id,
                  weight: index,
                  paramsName: item.paramsName,
                  paramsValue: item.paramsValue,
                  description: item.description,
                })
              })
              this.requestHeaderSource = weightList
            }
          }
        }
      },
      //校验规则
      getOptionRules(col) {
        if (['paramsName', 'paramsValue', 'description'].indexOf(col) !== -1) {
          // return [{required: true, message: '必填'}]
        } else if (col === 'columnName') {
          // return [
          //   { required: true, message: '必填!' },
          //   {
          //     validator: this.columnNameValidator,
          //     message: "字段名不能重复!",
          //     trigger: "blur"
          //   }]
        }
      },
      //tab页切换
      tabChange(key) {
        this.tableActiveKey = key
      },
      //表格单元格内容变化
      onCellChange(record, key, event) {

      },
      //输入框内容改变，给当前数据赋值
      handleChange(value, index, column, type) {
        if (type == 'requestParams') {
          this.$set(this.requestParamsSource[index], column, value)
        } else {
          this.$set(this.requestHeaderSource[index], column, value)
        }
      },
      //新增行
      handleAdd(type) {
        //先进行表单验证 验证成功后添加
        if (type == 'requestParams') {
          this.rpTableForm.validateFields((errors, values) => {
            if (!errors) {
              this.requestParamsSource.push({
                id: this.requestParamsSource[this.requestParamsSource.length - 1].id + 1,
              });
              this.requestParamsSource.forEach((item, index) => {
                this.requestParamsSource[index].weight = index
              })
              this.requestParamsCount++
            } else {
              return false;
            }
          })
        } else {
          this.rhTableForm.validateFields((errors, values) => {
            if (!errors) {
              this.requestHeaderSource.push({
                id: this.requestHeaderCount,
              });
              this.requestHeaderSource.forEach((item, index) => {
                this.requestHeaderSource[index].weight = index
              })
              this.requestHeaderCount++
            } else {
              return false;
            }
          })
        }
      },
      //删除
      handleDel(index, type) {
        if (type == 'requestParams') {
          this.requestParamsSource.splice(index, 1)
        } else {
          this.requestHeaderSource.splice(index, 1)
        }
      },
      //表格表单验证
      rhTableFormValidateData() {
        let key = false
        this.rhTableForm.validateFields((errors, values) => {
          if (!errors) {
            key = true
          } else {
            key = false
          }
        })
        return key;
      },
      //表格表单验证
      rpTableFormValidateData() {
        let key = false
        this.rpTableForm.validateFields((errors, values) => {
          if (!errors) {
            key = true
          } else {
            key = false
          }
        })
        return key;
      },
      //表单验证
      validateData() {
        let data = {}
        this.form.validateFields((errors, values) => {
          if (!errors) {
            data = values
          } else {
            data = null;
          }
        })
        return data;
      },
      //获取表单数据
      getData() {
        let formValue = this.form.getFieldsValue()
        let tableVlue = {
          requestParameters: JSON.stringify(this.requestParamsSource),
          requestHeadParameters: JSON.stringify(this.requestHeaderSource)
        }
        let pageData = {...formValue,...tableVlue}
        return pageData;
      },
    },
  }
</script>

<style scoped lang="less">
  .page-content {
    height: calc(100vh - 76px);
    margin: 10px;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    overflow: scroll;
    .page-main {
      width: 800px;
      height: 100%;
    }
  }

  /deep/ .ant-form-explain {
    display: none !important;
  }

  /deep/ div[class^="ant-table-wrapper"] .ant-table .ant-table-tbody tr, /deep/ div[class^="ant-table-wrapper"] .ant-table .ant-table-thead tr {
    height: 41px !important;
  }

  /deep/ .ant-tabs-ink-bar.ant-tabs-ink-bar-animated{
    width: 86px !important;
  }

  /deep/ .ant-table-bordered .ant-table-tbody>tr>td, /deep/ .ant-table-bordered .ant-table-thead>tr>th{
    border-right: none !important;
  }
</style>
